/*
 * @File name:
 * @Author: 1079161148@qq.com
 * @Version: V1.0
 * @Date: 2025-03-03 22:15:35
 * @Description:
 * Copyright (C) 2024-{year} Tsing Micro Technology Inc All rights reserved.
 */
import request from '@/utils/request'
import type { AxiosRequestConfig } from 'axios'

// API 响应接口
export interface ApiResponse<T = any> {
  code: number
  data: T
  message: string
}

// 用户信息接口
export interface UserInfo {
  id: number
  name: string
  avatar: string
}

// 添加朋友圈相关接口
export interface MomentItem {
  id: number
  userId: number
  userName: string
  avatar: string
  content: string
  images: string[]
  location: string
  likeCount: number
  commentCount: number
  createdAt: string
  isLiked: boolean
}

export interface MomentsResponse {
  list: MomentItem[]
  pagination: {
    page: number
    pageSize: number
    total: number
    hasMore: boolean
  }
}

// 确保接口返回的数据结构正确
interface PaginationResponse<T> {
  code: number
  data: {
    list: T[]
    pagination: {
      hasMore: boolean
      total: number
    }
  }
}

// 添加分页请求参数接口
interface PaginationParams {
  page: number
  pageSize: number
  keyword?: string // 添加可选的关键词参数
}

// API 类
export class Api {
  // 使用 axios
  static async login(data: { username: string; password: string }) {
    return request.post<ApiResponse<{ token: string; refreshToken: string }>>('/auth/login', data)
  }

  static async getUserInfo() {
    return request.get<ApiResponse<UserInfo>>('/user/info')
  }

  // 使用 fetch
  static async loginWithFetch(data: { username: string; password: string }) {
    return request.fetch.post('/auth/login', data)
  }

  static async getUserInfoWithFetch() {
    return request.fetch.get('/user/info')
  }

  // 自定义配置的请求
  static async customRequest<T>(config: AxiosRequestConfig) {
    return request.get<ApiResponse<T>>(config.url!, config)
  }

  // 流式请求
  static async streamRequest(url: string, options?: RequestInit) {
    const response = await fetch(url, {
      ...options,
      headers: {
        'Content-Type': 'application/json',
        ...options?.headers,
      },
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    return response.body
  }

  static async logout() {
    return request.post<ApiResponse<null>>('/auth/logout')
  }

  // 修改 getMoments 方法的参数类型
  static async getMoments(params: PaginationParams) {
    return request.get<PaginationResponse<MomentItem>>('/moments', { params })
  }

  static async uploadFile(formData: FormData) {
    return request.post<ApiResponse<{ url: string }>>('/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
}
